/*jshint esversion: 9 */
//http请求工具
import axios from "axios";
import Const from "./Const";
import router from '@/router';
import store from '@/store';
import { Dialog,Notify } from 'vant';

axios.defaults.timeout = 10000; //超时终止请求
axios.defaults.baseURL = Const.baseApiURL; //设置公共的请求前缀

// 请求拦截器
axios.interceptors.request.use(
    config => {
        config.headers[Const.TOKENKEY] = store.state.userModule.user.token || '';
        return config;
    },
    error => Promise.error(error),
);
//返回数据拦截
axios.interceptors.response.use(
    response => {
        const data = response.data;
        const state = data.state;
        switch (state) {
            case 200:
                return data;
            case 201: //表示登陆失效
                store.commit('userModule/setUser',{});
                //提示是否去登录
                Notify({  //提示报错信息
                    type: 'danger',
                    message: data.msg,
                    duration: 1000,
                });
                setTimeout(()=>{  //防止有两个dialog同时打开时的问题
                    Dialog.alert({  //提示是否去登录
                        title: '登录已失效',
                        message: '立即去登录',
                    }).then(() => {
                        router.push({
                            path:'/login',
                            query:{
                                from:router.history.current.fullPath,
                            },
                        });
                    });
                },0);
                return Promise.reject(data);
            default: //其他的返回失败
                return Promise.reject(data);
        }
    },
    () => { //数据请求发生错误
        return Promise.reject({
            msg: '请求发生错误',
        }); //返回接口返回的错误信息
    },
);

export function createRequest(method, url, param) { //获取一个请求
    if (!method || !url) return;
    switch (method) {
        case "get":
            return axios.get(url, {
                params: param,
            });
        case "put":
            return axios.put(url, param);
        case "delete":
            return axios.delete(url, param);
        case "post":
            return axios.post(url, param);
    }
}

//获取公用的格式化参数的方法方法
export function formatURLSearchParams(param = {}) { //普通表单
    if(param instanceof URLSearchParams) return param;
    let _param = new URLSearchParams();
    for (let index in param) {
        if (param[index] === undefined) break;
        _param.append(index, param[index]);
    }
    return _param;
}
export function formatFormData(param = {}) { //带有文件的表单
    if(param instanceof FormData) return param;
    let _param = new FormData();
    for (let index in param) {
        if (param[index] === undefined) break;
        _param.append(index, param[index]);
    }
    return _param;
}
export function formatUrlParams(param = {}) { //get的链接式参数
    let str = "?";
    for (let index in param) {
        if (param[index] === undefined) break;
        let _str;
        if (param[index] instanceof Object) {
            _str = encodeURIComponent(JSON.stringify(param[index])); //json序列化为字符串，并编码
        } else {
            _str = encodeURIComponent(param[index]);
        }
        str += index + '=' + _str + "&";
    }
    str = str.substr(0, str.length - 1);
    return str;
}